package com.chenzhou.common;

import com.chenzhou.entity.ProductEntity;

import java.sql.*;
import java.util.List;


/***
 * 模板模式设计baseDAO
 * @param <T>
 */
public abstract class BaseDAO<T> {

    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    /**
     * 获取数据库连接
     * @return
     */
    private Connection getConnection(){
        String url = "jdbc:mysql://localhost:3306/db_b2bsystem?characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection(url,"root","123456");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    /***
     * DAO查询方法封装，通用查询
     * @param sql
     * @param objects
     * @return
     */
    protected List<T> execute_Query(String sql,Object[] objects){
        conn = this.getConnection();
        try {
            ps = conn.prepareStatement(sql);
            this.setParameter(ps,objects);
            rs = ps.executeQuery();
            return resultToList(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                this.close_Connection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /***
     * 抽象方法处理返回结果
     * @param rs
     * @return
     * @throws SQLException
     */
    protected abstract List<T> resultToList(ResultSet rs) throws SQLException;



    /***
     * DAO增删改方法封装，通用
     * @param sql
     * @param objects
     * @return
     */
    protected int execute_Modify(String sql,Object[] objects){
        int flag = -1;
        conn = this.getConnection();
        try {
            ps = conn.prepareStatement(sql);
            this.setParameter(ps,objects);
            flag = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                this.close_Connection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /***
     * 为sql语句设置参数
     * @param ps
     * @param objects
     */
    private  void setParameter(PreparedStatement ps,Object[] objects) throws SQLException {
        if(null != objects){
            for (int i = 0; i < objects.length; i++) {
                ps.setObject(i+1,objects[i]);
            }
        }
    }

    /***
     * 关闭数据库连接
     */
    private void close_Connection() throws SQLException {
        if(rs!=null){
                rs.close();
        }
        if(ps!=null){
                ps.close();
        }
        if(conn!=null){
                conn.close();
        }
    }
}
